package com.winning.ds.login.controller;


import com.winning.ds.common.controller.BaseController;
import com.winning.ds.common.controller.CommonApi;
import com.winning.ds.common.entity.CommonJgUserEntity;
import com.winning.ds.common.entity.SysGncdEntity;
import com.winning.ds.common.entity.SysZcjgEntity;
import com.winning.ds.common.service.CommonApiService;
import com.winning.ds.common.util.Common;
import com.winning.ds.common.util.ResponseEntity;
import com.winning.ds.login.service.IndexService;
import com.winning.ds.login.entity.DbsxEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;


/**
 * @program: plat
 * @description: index controller
 * @author: nxs
 * @create: 2018-07-20 15:23
 **/
@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private CommonApiService commonApiService;

    @Autowired
    private CommonApi commonApi;

    /**
     * 根基当前登录机构编码--查询一级导航菜单
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/queryNavigationMenus", method = RequestMethod.GET)
    public ResponseEntity queryNavigationMenus() {
        List<SysGncdEntity> list = indexService.queryNavigationMenus(indexService.getJsbmList());
        CommonJgUserEntity user=getUser();
        //platAdmin没有权限时加上系统管理菜单
        if (list.size()==0&&user != null && "platAdmin".equals(user.getDldm())) {
            list=indexService.queryMenu("9804");
        }
        return ResponseEntity.ok().put("menulist", list);
    }

    /**
     * 查询一级，二级菜单
     */
    @RequestMapping(value = "/queryNavigationVueMenus", method = RequestMethod.GET)
    public ResponseEntity queryNavigationVueMenus() {
        List<SysGncdEntity> list = indexService.queryNavigationMenus(indexService.getJsbmList());

        if(CollectionUtils.isNotEmpty(list)){
            for (SysGncdEntity sysGncdEntity : list) {
                //取二级菜单
                Map<String, Object> menuMap = indexService.querySubMenu(sysGncdEntity.getMcode());
                List<SysGncdEntity> secondList=(List)menuMap.get("secondMenu");
                //platAdmin没有权限时加上系统管理菜单
                if(CollectionUtils.isNotEmpty(secondList)){
                    sysGncdEntity.setThirdlist(secondList);
                }
            }

        }
        return ResponseEntity.ok().put("menulist", list);
    }

    /**
     * 根基当前登录机构编码--查询一级导航菜单
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/queryNavigationMenu", method = RequestMethod.GET)
    public ResponseEntity queryNavigationMenu() {
        List<SysGncdEntity> list = indexService.queryNavigationMenu(indexService.getJsbmList());
        CommonJgUserEntity user=getUser();
        //platAdmin没有权限时加上系统管理菜单
        if (list.size()==0&&user != null && "platAdmin".equals(user.getDldm())) {
            list=indexService.queryMenu("9804");
        }

        return ResponseEntity.ok().put("menulist", list);

    }

    /**
     * @Author: nxs@winning.com.cn
     * @Description: 查询二，三级菜单
     * @Date: 2018-07-27 15:40:41
     **/
    @RequestMapping(value = "/querySubMenu/{mcode}", method = RequestMethod.GET)
    public ResponseEntity querySubMenu(@PathVariable String mcode) {
        if (!Common.validateParams(mcode)) {
            return ResponseEntity.error(201, "菜单不能为空");
        }
        //查询菜单
        Map<String, Object> menuMap = indexService.querySubMenu(mcode);

        CommonJgUserEntity user=getUser();
        List<SysGncdEntity> secondList=(List)menuMap.get("secondMenu");
        //platAdmin没有权限时加上系统管理菜单
        if (secondList.size()==0&&user != null && "platAdmin".equals(user.getDldm())) {
            menuMap=indexService.queryXtglMenu("9804");
        }

        return ResponseEntity.ok(menuMap);

    }


    /**
     *查询用户的权限菜单
     */
    @RequestMapping(value = "/getGncdTree", method = RequestMethod.GET)
    public ResponseEntity getGncdTree()throws IOException{
        CommonJgUserEntity principal = (CommonJgUserEntity) SecurityUtils.getSubject().getPrincipal();
        String zclsh = principal.getZclsh();
        List<SysGncdEntity> sysGncdEntitys = indexService.queryGncd(zclsh, "912","DS");
        List<SysGncdEntity> tree = getTree("912",sysGncdEntitys);
        return ResponseEntity.ok().put("tree", tree);
    }

    /**
     * 构造菜单树
     */
    private List<SysGncdEntity> getTree(String pCode, List<SysGncdEntity> cds) {
        List<SysGncdEntity> cdTree = new ArrayList<SysGncdEntity>();
        for (SysGncdEntity cd: cds){
            if(pCode.equals(cd.getPcode()==null?"":cd.getPcode())){
                cd.setThirdlist(getTree(cd.getMcode(),cds));
                cdTree.add(cd);
            }
        }
        return cdTree;
    }

    @RequestMapping(value = "/updateRootJgbm/{jgbm}", method = RequestMethod.POST)
    public ResponseEntity updateRootJgbm(@PathVariable String jgbm) {
        if (!Common.validateParams(jgbm)) {
            return ResponseEntity.error(201, "机构编码不能为空");
        }
        indexService.updateRootJgbm(jgbm);
        return ResponseEntity.ok();

    }

    /**
     * 修改默认省
     *
     * @return
     */
    @RequestMapping(value = "/updateDefaultSheng/{csz}", method = RequestMethod.POST)
    public ResponseEntity updateDefaultSheng(@PathVariable String csz) {
        if (!Common.validateParams(csz)) {
            return ResponseEntity.error(201, "默认省不能为空");
        }
        indexService.updateDefaultSheng(csz);
        return ResponseEntity.ok();
    }

    /**
     * 主页面数据统计
     *
     * @return
     */
    @RequestMapping(value ="/hc/{lb}", method = RequestMethod.GET)
    public ResponseEntity homeCount(@PathVariable String lb) {

        ResponseEntity response = ResponseEntity.ok();
        Map queryParams = new HashMap();
        ResponseEntity jgbm = commonApi.Jgbm();
        String yljgdm =(String) jgbm.get("jgbm");
        queryParams.put("yljgdm", yljgdm);
        queryParams.put("jgbm", yljgdm);

        if(lb.equals("zcjg")){
            Integer jgTotalNum = indexService.queryJgTotalNum(queryParams);
            response.put("jgcount", jgTotalNum);
        }

        if(lb.equals("yhry")){
            Integer yhryTotalNum = indexService.queryYhryTotalNum(queryParams);
            response.put("yhcount", yhryTotalNum);
        }

        if(lb.equals("bzxz")){
            Integer templateNum = indexService.queryTemplateNum(queryParams);
            response.put("tecount", templateNum);
        }

        if(lb.equals("mldz")){
            Integer mlMapping = indexService.queryMlMapping();
            response.put("mlcount", mlMapping);
        }


        if(lb.equals("zydz")){
            Integer termMapping = indexService.queryTermMapping();
            response.put("termcount", termMapping);
        }

        return response;
    }


    /**
     * 得到下载专区列表
     *
     * @return
     */
    @RequestMapping(value = "/dl", method = RequestMethod.GET)
    public ResponseEntity downList(HttpServletRequest request, @RequestParam Map queryParams) throws IOException {
        ResponseEntity response = ResponseEntity.ok();
        return response;
    }

    /**
     * 得到待办事项
     *
     * @return
     */

    @RequestMapping(value = "/dbsx/{lb}", method = RequestMethod.GET)
    public ResponseEntity dbsxList(@PathVariable String lb) throws IOException {
        ResponseEntity response = ResponseEntity.ok();
        ResponseEntity jgbm = commonApi.Jgbm();
        Map queryParams =new HashMap();
        String yljgdm =(String) jgbm.get("jgbm");
        queryParams.put("yljgdm", yljgdm);
        queryParams.put("jgbm", yljgdm);
        queryParams.put("lb", lb);

        DbsxEntity dbsxEntity= indexService.dbsxList(queryParams);

        response.put("data", dbsxEntity);
        return response;
    }



    /**
     * 查询机构及其子机构信息集
     * @return
     */
    public List<SysZcjgEntity> queryCurAndSubJg(Map option) {

        if (!Objects.isNull(option) && !StringUtils.isEmpty((String) option.get("yljgbm"))) {
            return querySubJg((String) option.get("yljgbm"));
        }
        ResponseEntity jgbm = commonApi.Jgbm();
        List<SysZcjgEntity> list = querySubJg((String) jgbm.get("jgbm"));
        return list;
    }

    /**
     * 查询子机构
     * @param jgbm
     * @return
     */
    public List<SysZcjgEntity> querySubJg(String jgbm) {

        if (StringUtils.isEmpty(jgbm)) {
            return queryCurAndSubJg(null);
        }
        List<SysZcjgEntity> list = new ArrayList<SysZcjgEntity>();
        SysZcjgEntity syszcjgeneity = commonApiService.getJgInfo(jgbm);

            ResponseEntity subjgbm = commonApi.jgSubInfo(jgbm);
            list = ( List<SysZcjgEntity>)subjgbm.get("list");

        list.add(syszcjgeneity);
        return list;
    }


    /**
     * 下载文件
     *
     * @param name 文件名
     */
    @RequestMapping("/dw")
    public void download(String name, HttpServletResponse response) throws IOException {
        String file = System.getProperty("user.dir") + File.separator + "upload" + File.separator + URLDecoder.decode(name);
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = Files.readAllBytes(Paths.get(file));
        outputStream.write(bytes);
        outputStream.close();
    }


    /**
     * 文档管理-下载文件
     * @param
     * @param response
     * @param
     *//**/
    @RequestMapping(value = "/exportFile", method = RequestMethod.GET)
    public  void exportFile(String filename, HttpServletRequest request, HttpServletResponse response) {

        commonApi.exportFile(filename,request,response);
    }

    /**
     * 文档管理-获取文件路径 下载之前先判断有没有该文档
     * @param filename
     *//**/
    @RequestMapping(value = "/getFilePath", method = RequestMethod.GET)
    @ResponseBody
    public  ResponseEntity getFilePath(String filename) {
        ResponseEntity responseEntity = ResponseEntity.ok();
        String filePath = commonApi.getFileName(filename);
        if(StringUtils.equalsIgnoreCase("",filePath)){
            return ResponseEntity.error(500,"未找到文件");
        }
        responseEntity.put("filepath",filePath);
       return responseEntity;
    }

    /**
     * @vsts_no：
     * @comment： 查询首页得卡牌信息
     * @author： caopengfei
     * @time：  2020/3/13 14:46
     */
    @GetMapping("queryCard")
    public ResponseEntity queryCard(){
        Map<String,Object> cardValues  = indexService.queryCard();
      return ResponseEntity.ok().put("data",cardValues);
    }

    /**
     * @vsts_no：
     * @comment： 查询市级数据画像
     * @author： caopengfei
     * @time：  2020/3/13 14:46
     */
    @GetMapping("querySjsjhx")
    public ResponseEntity querySjsjhx(){
        Map<String,String> perValues = indexService.querySjsjhx();
        return  ResponseEntity.ok().put("data",perValues);
    }


    /**
     * @vsts_no：
     * @comment： 查询导出日志
     * @author： caopengfei
     * @time：  2020/3/13 14:48
     */
    @GetMapping("queryDcrz")
    public ResponseEntity queryDcrz(){
        List<Map<String,Object>> queryList = indexService.queryDcrz();
        return  ResponseEntity.ok().put("rows",queryList);
    }

    /**
     *添加帮助文档
     */
    @ResponseBody
    @RequestMapping(value = "addHelpHtml", method = RequestMethod.POST)
    public ResponseEntity addHelpHtml( @RequestBody Map<String, Object> queryParams) {
        try {
            indexService.addHelpHtml(queryParams);
        } catch (Exception e) {
            return ResponseEntity.error("不能重复新增");
        }
        return ResponseEntity.ok();
    }

    /**
     *查询帮助文档
     */
    @ResponseBody
    @RequestMapping(value = "getHelpHtml", method = RequestMethod.POST)
    public ResponseEntity getHelpHtml( @RequestBody Map<String, Object> queryParams) {
        List<Map<String,Object>> queryList = indexService.getHelpHtml(queryParams);
        return  ResponseEntity.ok().put("data",queryList);
    }

    @ResponseBody
    @RequestMapping(value = "updateHelpHtml", method = RequestMethod.POST)
    public ResponseEntity updateHelpHtml( @RequestBody Map<String, Object> queryParams) {
        indexService.updateHelpHtml(queryParams);
        return  ResponseEntity.ok();
    }
}
